import { createStore, Store, useStore as baseUseStore } from 'vuex'
import { InjectionKey } from 'vue'
import { IUserInfo } from '@/api/types/common'
import { getItem, setItem } from '@/utils/storage'
import { USER } from '@/utils/constants'

// 定义 injection key
export const key: InjectionKey<Store<State>> = Symbol('store')

const state = {
    isCollapse: false,
    user: getItem<{ token: string } & IUserInfo>(USER) as null | IUserInfo,  // 定义 user 类型为 null，防止 undefined 类型检查
}
export type State = typeof state

export const store = createStore<State>({
    state,
    getters: {},
    mutations: {
        setIsCollapse(state: State, collapse: boolean) {
            state.isCollapse = collapse
        },
        setUser(state: State, payload: IUserInfo) {
            state.user = payload
            setItem(USER, JSON.stringify(payload))
        }
    },
    actions: {},
    modules: {}
})

export function useStore () {
    return baseUseStore(key)
  }